<template>
  <div class="task-list-container">
    <!-- 顶部导航栏 -->
    <div class="top-navbar">
      <div class="nav-left">
        <div class="app-title">
          <div class="title-icon">
            <el-icon><VideoPlay /></el-icon>
          </div>
          <div class="title-content">
            <h1 class="title-text">M3U8 Downloader</h1>
            <span class="title-subtitle">专业的M3U8视频下载工具</span>
          </div>
        </div>
      </div>
      <div class="nav-right">
        <el-button 
          @click="goToSettings" 
          :icon="Setting" 
          type="text"
          class="nav-btn"
        >
          设置
        </el-button>
        <el-button 
          @click="showNewTaskDialog" 
          type="primary" 
          :icon="Plus"
          class="primary-btn"
        >
          新建下载任务
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-section">
      <div class="stats-grid">
        <div class="stat-card active">
          <div class="stat-icon active-icon">
            <el-icon><VideoPlay /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ activeTasks.length }}</div>
            <div class="stat-label">进行中</div>
          </div>
        </div>
        <div class="stat-card completed">
          <div class="stat-icon completed-icon">
            <el-icon><CircleCheck /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ completedTasks.length }}</div>
            <div class="stat-label">已完成</div>
          </div>
        </div>
        <div class="stat-card failed">
          <div class="stat-icon failed-icon">
            <el-icon><CircleClose /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ failedTasks.length }}</div>
            <div class="stat-label">失败</div>
          </div>
        </div>
        <div class="stat-card paused">
          <div class="stat-icon paused-icon">
            <el-icon><VideoPause /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ pausedTasks.length }}</div>
            <div class="stat-label">已暂停</div>
          </div>
        </div>
        <div class="stat-card pending">
          <div class="stat-icon pending-icon">
            <el-icon><Clock /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ pendingTasks.length }}</div>
            <div class="stat-label">等待中</div>
          </div>
        </div>
      </div>
    </div>

    <!-- Tab切换 -->
    <div class="tab-section">
      <div class="tab-container">
        <div class="tab-header">
          <div 
            class="tab-item" 
            :class="{ active: activeTab === 'all' }"
            @click="activeTab = 'all'"
          >
            <el-icon><List /></el-icon>
            <span>全部任务</span>
            <el-badge 
              :value="tasks.length" 
              class="tab-badge"
            />
          </div>
          <div 
            class="tab-item" 
            :class="{ active: activeTab === 'downloading' }"
            @click="activeTab = 'downloading'"
          >
            <el-icon><Download /></el-icon>
            <span>下载中</span>
            <el-badge 
              v-if="getDownloadingCount() > 0" 
              :value="getDownloadingCount()" 
              class="tab-badge"
            />
          </div>
          <div 
            class="tab-item" 
            :class="{ active: activeTab === 'completed' }"
            @click="activeTab = 'completed'"
          >
            <el-icon><CircleCheck /></el-icon>
            <span>已完成</span>
            <el-badge 
              v-if="getCompletedCount() > 0" 
              :value="getCompletedCount()" 
              class="tab-badge"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 任务表格卡片 -->
    <div class="table-section">
      <el-card class="task-table-card" shadow="never">
        <template #header>
          <div class="card-header">
            <div class="header-left">
              <span class="card-title">{{ getTabTitle() }}</span>
              <span class="task-count">共 {{ currentTasks.length }} 个任务</span>
            </div>
            <div class="header-actions">
              <el-button 
                @click="refreshTasks" 
                :icon="Refresh" 
                type="text"
                class="action-btn"
              >
                刷新
              </el-button>
              <el-button 
                @click="testEventListeners" 
                :icon="VideoPlay" 
                type="text"
                class="action-btn"
              >
                测试进度
              </el-button>
              <el-button 
                @click="testReactivity" 
                :icon="Setting" 
                type="text"
                class="action-btn"
              >
                测试响应式
              </el-button>
              <el-button 
                @click="forceRefreshTasks" 
                :icon="Refresh" 
                type="text"
                class="action-btn"
              >
                强制刷新
              </el-button>
              <el-button 
                @click="clearCompleted" 
                type="warning" 
                :icon="Delete"
                class="action-btn warning"
              >
                清理已完成
              </el-button>
            </div>
          </div>
        </template>
        
        <el-table 
          :data="currentTasks" 
          style="width: 100%" 
          v-loading="loading"
          @row-dblclick="handleRowDoubleClick"
          class="task-table"
          :row-class-name="getRowClassName"
          :row-key="(row) => row.id || row.filename"
        >
          <el-table-column prop="filename" label="文件名" min-width="250">
            <template #default="{ row }">
              <div class="filename-cell">
                <div class="file-info">
                  <span class="filename">{{ row.filename }}</span>
                  <div class="file-meta">
                    <span class="file-size" v-if="row.totalSize">
                      {{ formatFileSize(row.totalSize) }}
                    </span>
                    <span class="file-duration" v-if="row.duration">
                      {{ formatDuration(row.duration) }}
                    </span>
                  </div>
                </div>
                <div class="file-tags">
                  <el-tag v-if="row.status === 'completed'" type="success" size="small" class="file-tag">
                    MP4
                  </el-tag>
                  <el-tag v-if="row.concurrentThreads > 1" type="info" size="small" class="file-tag">
                    {{ row.concurrentThreads }}线程
                  </el-tag>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="status" label="状态" width="120">
            <template #default="{ row }">
              <div class="status-cell">
                <el-tag :type="getStatusType(row.status)" size="small" class="status-tag">
                  {{ getStatusText(row.status) }}
                </el-tag>
                <div class="status-time" v-if="row.status === 'completed'">
                  {{ formatTime(row.completedTime) }}
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="progress" label="进度" width="220">
            <template #default="{ row }">
              <div class="progress-cell">
                <div class="progress-header">
                  <span class="progress-percentage">{{ getDisplayProgress(row) }}%</span>
                  <span class="progress-segments" v-if="row.totalSegments > 0">
                    {{ row.downloadedSegments || 0 }}/{{ row.totalSegments }}
                  </span>
                </div>
                <el-progress 
                  :percentage="getDisplayProgress(row)" 
                  :status="getProgressStatus(row.status)"
                  :stroke-width="6"
                  class="custom-progress"
                />
                <div class="progress-details">
                  <span class="size-info">
                    {{ formatFileSize(row.downloadedSize || 0) }} / {{ formatFileSize(row.totalSize || 0) }}
                  </span>
                  <span v-if="shouldShowDownloadSpeed && row.status === 'downloading'" class="speed-info">
                    <el-icon class="speed-icon"><Download /></el-icon>
                    {{ formatDownloadSpeed(getDownloadSpeed(row.id)) }}
                  </span>
                  <span v-if="row.status === 'downloading' && getDisplayProgress(row) > 0" class="remaining-time">
                    剩余: {{ formatRemainingTime(calculateRemainingTime(row.id)) }}
                  </span>
                  <span v-if="row.status === 'merging' && row.mergeProgress > 0" class="merge-info">
                    合并中: {{ row.mergeProgress }}%
                  </span>
                </div>
                <!-- 添加分片信息显示 -->
                <div v-if="row.totalSegments > 0 && row.status === 'downloading'" class="segments-info">
                  <span class="segments-text">
                    分片: {{ row.downloadedSegments || 0 }}/{{ row.totalSegments }}
                  </span>
                  <span v-if="row.failedSegments && row.failedSegments.length > 0" class="failed-segments">
                    失败: {{ row.failedSegments.length }}
                  </span>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="concurrentThreads" label="线程数" width="80" align="center">
            <template #default="{ row }">
              <div class="threads-cell">
                <span class="threads-number">{{ row.concurrentThreads }}</span>
                <span class="threads-label">线程</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="startTime" label="开始时间" width="160">
            <template #default="{ row }">
              <div class="time-cell">
                <div class="start-time">{{ formatTime(row.startTime) }}</div>
                <div class="duration" v-if="row.startTime && row.completedTime">
                  {{ formatDuration(row.completedTime - row.startTime) }}
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="240" fixed="right">
            <template #default="{ row }">
              <div class="actions-cell">
                <el-button 
                  v-if="row.status === 'pending'"
                  @click="startTask(row.id)" 
                  type="primary" 
                  size="small"
                  :icon="VideoPlay"
                  class="action-btn"
                >
                  开始
                </el-button>
                <el-button 
                  v-if="row.status === 'downloading' || row.status === 'parsing'"
                  @click="pauseTask(row.id)" 
                  type="warning" 
                  size="small"
                  :icon="VideoPause"
                  class="action-btn"
                >
                  暂停
                </el-button>
                <el-button 
                  v-if="row.status === 'paused'"
                  @click="resumeTask(row.id)" 
                  type="success" 
                  size="small"
                  :icon="VideoPlay"
                  class="action-btn"
                >
                  继续
                </el-button>
                <el-button 
                  v-if="row.status === 'error'"
                  @click="retryTask(row.id)" 
                  type="primary" 
                  size="small"
                  :icon="Refresh"
                  class="action-btn"
                >
                  重试
                </el-button>
                <el-button 
                  @click="viewTaskDetail(row.id)" 
                  type="info" 
                  size="small"
                  :icon="View"
                  class="action-btn"
                >
                  详情
                </el-button>
                <el-button 
                  @click="debugProgress(row)" 
                  type="warning" 
                  size="small"
                  :icon="Setting"
                  class="action-btn"
                  title="调试进度信息"
                >
                  调试
                </el-button>
                <el-button 
                  @click="deleteTask(row.id)" 
                  type="danger" 
                  size="small"
                  :icon="Delete"
                  class="action-btn"
                >
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 新建任务对话框 -->
    <NewTaskDialog 
      v-model:visible="newTaskDialogVisible" 
      @task-created="handleTaskCreated"
    />
  </div>
</template>

<script setup>
import { ref, onMounted,computed } from 'vue'
import { useRouter } from 'vue-router'
import { useTaskStore } from '../stores/taskStore'
import { useSettingsStore } from '../stores/settingsStore'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  VideoPlay, 
  Plus, 
  Setting, 
  Refresh, 
  Delete, 
  VideoPause, 
  VideoPlay as VideoPlayIcon,
  CircleCheck,
  CircleClose,
  VideoPause as VideoPauseIcon,
  Clock,
  View,
  List,
  Download
} from '@element-plus/icons-vue'
import NewTaskDialog from '../components/NewTaskDialog.vue'

const router = useRouter()
const taskStore = useTaskStore()
const settingsStore = useSettingsStore()
const loading = ref(false)
const newTaskDialogVisible = ref(false)

// 使用计算属性确保响应式更新，按时间倒序排列
const tasks = computed(() => {
  // 检查taskStore是否已初始化
  if (!taskStore.tasks || !Array.isArray(taskStore.tasks)) {
    return []
  }
  const allTasks = taskStore.tasks
  return [...allTasks].sort((a, b) => {
    // 按开始时间倒序排列（最新的在前面）
    const timeA = a.startTime || 0
    const timeB = b.startTime || 0
    return timeB - timeA
  })
})

const activeTasks = computed(() => {
  // 检查taskStore是否已初始化
  if (!taskStore.tasks || !Array.isArray(taskStore.tasks)) {
    return []
  }
  const allTasks = taskStore.tasks
  return allTasks.filter(t => ['pending', 'parsing', 'downloading', 'merging'].includes(t.status))
})

const completedTasks = computed(() => {
  // 检查taskStore是否已初始化
  if (!taskStore.tasks || !Array.isArray(taskStore.tasks)) {
    return []
  }
  const allTasks = taskStore.tasks
  return allTasks.filter(t => t.status === 'completed')
})

const failedTasks = computed(() => {
  // 检查taskStore是否已初始化
  if (!taskStore.tasks || !Array.isArray(taskStore.tasks)) {
    return []
  }
  const allTasks = taskStore.tasks
  return allTasks.filter(t => t.status === 'error')
})

const pausedTasks = computed(() => {
  // 检查taskStore是否已初始化
  if (!taskStore.tasks || !Array.isArray(taskStore.tasks)) {
    return []
  }
  const allTasks = taskStore.tasks
  return allTasks.filter(t => t.status === 'paused')
})

const { 
  pauseTask: pauseTaskStore,
  resumeTask: resumeTaskStore,
  deleteTask: deleteTaskStore,
  retryTask: retryTaskStore,
  startTask: startTaskStore,
  formatFileSize,
  formatDownloadSpeed,
  getDownloadSpeed,
  calculateRemainingTime,
  formatRemainingTime
} = taskStore

// 计算pending任务
const pendingTasks = computed(() => {
  // 检查taskStore是否已初始化
  if (!taskStore.tasks || !Array.isArray(taskStore.tasks)) {
    return []
  }
  const allTasks = taskStore.tasks
  return allTasks.filter(t => t.status === 'pending')
})

const { shouldShowDownloadSpeed } = settingsStore

const activeTab = ref('all')

// 获取下载中任务数量
const getDownloadingCount = () => {
  return activeTasks.value.length
}

// 获取已完成任务数量
const getCompletedCount = () => {
  return completedTasks.value.length
}

// 计算属性包装，确保响应式更新
const currentTasks = computed(() => {
  // 添加强制刷新依赖
  forceRefresh.value
  
  // 检查taskStore是否已初始化
  if (!taskStore.tasks || !Array.isArray(taskStore.tasks)) {
    console.warn('taskStore.tasks is not available or not an array:', taskStore.tasks)
    return []
  }
  const allTasks = taskStore.tasks
  console.log('currentTasks computed - activeTab:', activeTab.value, 'allTasks length:', allTasks.length)
  
  let filteredTasks = []
  switch (activeTab.value) {
    case 'downloading':
      filteredTasks = allTasks.filter(t => 
        ['pending', 'parsing', 'downloading', 'merging'].includes(t.status)
      )
      break
    case 'completed':
      filteredTasks = allTasks.filter(t => t.status === 'completed')
      break
    default:
      filteredTasks = allTasks
  }
  
  // 确保返回的始终是数组
  if (!Array.isArray(filteredTasks)) {
    console.warn('Filtered tasks is not an array:', filteredTasks)
    return []
  }
  
  console.log('currentTasks returning:', filteredTasks.length, 'tasks')
  return filteredTasks
})

// 添加强制刷新机制
const forceRefresh = ref(0)
const forceRefreshTasks = () => {
  forceRefresh.value++
  console.log('Force refresh triggered, count:', forceRefresh.value)
}

// 获取tab标题
const getTabTitle = () => {
  switch (activeTab.value) {
    case 'downloading':
      return '下载中任务'
    case 'completed':
      return '已完成任务'
    default:
      return '下载任务列表'
  }
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    'pending': 'warning',
    'parsing': 'info',
    'downloading': 'primary',
    'merging': 'warning',
    'completed': 'success',
    'error': 'danger',
    'paused': 'info'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '等待中',
    'parsing': '解析中',
    'downloading': '下载中',
    'merging': '合并中',
    'completed': '已完成',
    'error': '失败',
    'paused': '已暂停'
  }
  return statusMap[status] || status
}

// 获取进度状态
const getProgressStatus = (status) => {
  if (status === 'error') return 'exception'
  if (status === 'completed') return 'success'
  return undefined
}

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return '-'
  return new Date(timestamp).toLocaleString('zh-CN')
}

// 格式化时长
const formatDuration = (seconds) => {
  if (seconds === null || seconds === undefined) return '-'
  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  const s = Math.floor(seconds % 60)
  const parts = []
  if (h > 0) parts.push(`${h}小时`)
  if (m > 0) parts.push(`${m}分钟`)
  if (s > 0 || parts.length === 0) parts.push(`${s}秒`)
  return parts.join('')
}

// 显示新建任务对话框
const showNewTaskDialog = () => {
  newTaskDialogVisible.value = true
}

// 处理任务创建
const handleTaskCreated = (task) => {
  console.log('Task created:', task)
}

// 跳转到设置页面
const goToSettings = () => {
  router.push('/settings')
}

// 启动任务
const startTask = async (taskId) => {
  try {
    await startTaskStore(taskId)
    ElMessage.success('任务已开始')
  } catch (error) {
    ElMessage.error('启动任务失败: ' + error.message)
  }
}

// 暂停任务
const pauseTask = async (taskId) => {
  try {
    await pauseTaskStore(taskId)
    ElMessage.success('任务已暂停')
  } catch (error) {
    ElMessage.error('暂停任务失败')
  }
}

// 恢复任务
const resumeTask = async (taskId) => {
  try {
    await resumeTaskStore(taskId)
    ElMessage.success('任务已恢复')
  } catch (error) {
    ElMessage.error('恢复任务失败')
  }
}

// 重试失败的任务
const retryTask = async (taskId) => {
  try {
    await retryTaskStore(taskId)
    ElMessage.success('任务已重新开始')
  } catch (error) {
    ElMessage.error('重试任务失败: ' + error.message)
  }
}

// 查看任务详情
const viewTaskDetail = (taskId) => {
  router.push(`/task/${taskId}`)
}

// 打开文件
const openFile = async (taskId) => {
  try {
    const task = tasks.value.find(t => t.id === taskId)
    if (task && task.outputFile) {
      if (window.electronAPI && window.electronAPI.openFile) {
        const result = await window.electronAPI.openFile(task.outputFile)
        if (result.success) {
          ElMessage.success('文件已打开')
        } else {
          throw new Error(result.error)
        }
      } else {
        ElMessage.info('文件路径: ' + task.outputFile)
      }
    } else {
      ElMessage.warning('文件不存在')
    }
  } catch (error) {
    ElMessage.error('打开文件失败: ' + error.message)
  }
}

// 打开文件所在位置
const openFileLocation = async (taskId) => {
  try {
    const task = tasks.value.find(t => t.id === taskId)
    if (task && task.outputFile) {
      if (window.electronAPI && window.electronAPI.openFileLocation) {
        const result = await window.electronAPI.openFileLocation(task.outputFile)
        if (result.success) {
          ElMessage.success('已打开文件所在位置')
        } else {
          throw new Error(result.error)
        }
      } else {
        ElMessage.info('文件位置: ' + task.outputFile)
      }
    } else {
      ElMessage.warning('文件不存在')
    }
  } catch (error) {
    ElMessage.error('打开文件位置失败: ' + error.message)
  }
}

// 双击行处理
const handleRowDoubleClick = (row) => {
  if (row.status === 'completed' && row.outputFile) {
    openFile(row.id)
  } else {
    viewTaskDetail(row.id)
  }
}

// 删除任务
const deleteTask = async (taskId) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个任务吗？删除后无法恢复。',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteTaskStore(taskId)
    ElMessage.success('任务已删除')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除任务失败: ' + error.message)
    }
  }
}

// 刷新任务
const refreshTasks = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    ElMessage.success('刷新完成')
  }, 1000)
}

// 清理已完成任务
const clearCompleted = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清理所有已完成的任务吗？',
      '确认清理',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const completedIds = completedTasks.value.map(task => task.id)
    let successCount = 0
    let failCount = 0
    
    // 逐个删除任务，等待每个操作完成
    for (const id of completedIds) {
      try {
        await deleteTaskStore(id)
        successCount++
      } catch (error) {
        console.error(`Failed to delete task ${id}:`, error)
        failCount++
      }
    }
    
    if (failCount > 0) {
      ElMessage.warning(`清理完成：成功 ${successCount} 个，失败 ${failCount} 个`)
    } else {
      ElMessage.success(`已清理 ${successCount} 个已完成任务`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('清理任务失败: ' + error.message)
    }
  }
}

// 测试事件监听器
const testEventListeners = () => {
  console.log('Testing event listeners...')
  console.log('window.electronAPI available:', !!window.electronAPI)
  
  if (window.electronAPI) {
    console.log('Electron API methods:', Object.keys(window.electronAPI))
    
    // 创建一个测试任务
    const testTask = taskStore.createTask({
      filename: '测试任务',
      url: 'https://example.com/test.m3u8',
      outputPath: '/tmp/test'
    })
    
    
    // 模拟进度更新 - 逐步增加进度
    let progress = 0
    let downloadedSize = 0
    const totalSize = 50 * 1024 * 1024 // 50MB
    const totalSegments = 100
    let downloadedSegments = 0
    
    const progressInterval = setInterval(() => {
      progress += 2
      downloadedSize = Math.floor((totalSize * progress) / 100)
      downloadedSegments = Math.floor((totalSegments * progress) / 100)
      
      console.log(`Simulating progress update: ${progress}%`)
      console.log(`Downloaded size: ${downloadedSize} / ${totalSize}`)
      console.log(`Downloaded segments: ${downloadedSegments} / ${totalSegments}`)
      
      // 模拟下载速度变化
      const downloadSpeed = Math.random() * 1024 * 1024 + 512 * 1024 // 512KB/s - 1.5MB/s
      
      // 模拟分片信息
      const segments = []
      for (let i = 0; i < totalSegments; i++) {
        segments.push({
          index: i,
          size: Math.floor(totalSize / totalSegments),
          url: `https://example.com/segment_${i}.ts`
        })
      }
      
      taskStore.updateTask(testTask.id, {
        status: 'downloading',
        progress: progress,
        downloadedSize: downloadedSize,
        totalSize: totalSize,
        downloadedSegments: downloadedSegments,
        totalSegments: totalSegments,
        segments: segments
      })
      
      // 更新下载速度
      taskStore.updateDownloadSpeed(testTask.id, downloadSpeed)
      
      if (progress >= 100) {
        clearInterval(progressInterval)
        // 模拟完成
        setTimeout(() => {
          taskStore.updateTask(testTask.id, {
            status: 'completed',
            progress: 100,
            outputFile: '/tmp/test/测试任务.mp4'
          })
        }, 1000)
        
        // 清理测试任务
        setTimeout(() => {
          taskStore.deleteTask(testTask.id)
        }, 3000)
      }
    }, 200)
  } else {
    console.error('Electron API not available')
    ElMessage.error('Electron API 不可用')
  }
}

// 测试响应式更新
const testReactivity = () => {
  console.log('=== Testing Reactivity ===')
  console.log('Current tasks count:', tasks.value.length)
  console.log('Current active tasks count:', activeTasks.value.length)
  console.log('Current completed tasks count:', completedTasks.value.length)
  console.log('Current currentTasks count:', currentTasks.value.length)
  
  // 创建一个简单的测试任务
  const testTask = taskStore.createTask({
    filename: '响应式测试任务',
    url: 'https://example.com/reactivity-test.m3u8',
    outputPath: '/tmp/test',
    autoStart: false
  })
  
  console.log('Created test task:', testTask.id)
  console.log('Tasks after creation:', tasks.value.length)
  console.log('Current tasks after creation:', currentTasks.value.length)
  
  // 模拟进度更新
  let progress = 0
  const progressInterval = setInterval(() => {
    progress += 10
    console.log(`Updating test task progress to ${progress}%...`)
    
    taskStore.updateTask(testTask.id, {
      status: 'downloading',
      progress: progress,
      downloadedSize: (4 * 1024 * 1024 * progress) / 100,
      totalSize: 4 * 1024 * 1024,
      downloadedSegments: Math.floor((20 * progress) / 100),
      totalSegments: 20
    })
    
    // 强制刷新视图
    forceRefreshTasks()
    
    console.log('Tasks after update:', tasks.value.length)
    console.log('Current tasks after update:', currentTasks.value.length)
    
    if (progress >= 100) {
      clearInterval(progressInterval)
      
      // 模拟完成
      setTimeout(() => {
        taskStore.updateTask(testTask.id, {
          status: 'completed',
          progress: 100,
          outputFile: '/tmp/test/响应式测试任务.mp4'
        })
        
        // 清理测试任务
        setTimeout(() => {
          taskStore.deleteTask(testTask.id)
          console.log('=== Reactivity test completed ===')
        }, 2000)
      }, 1000)
    }
  }, 500)
}

onMounted(async () => {
  await taskStore.initialize()
  settingsStore.initialize()
})

// 获取行样式类名
const getRowClassName = ({ row }) => {
  if (row.status === 'completed') return 'row-completed'
  if (row.status === 'error') return 'row-error'
  if (row.status === 'paused') return 'row-paused'
  if (row.status === 'downloading') return 'row-downloading'
  return ''
}

// 获取显示进度
const getDisplayProgress = (row) => {
  // 如果任务已完成，显示100%
  if (row.status === 'completed') return 100
  
  // 如果任务出错，显示0%
  if (row.status === 'error') return 0
  
  // 如果任务暂停，保持当前进度
  if (row.status === 'paused') return row.progress || 0
  
  // 对于下载中的任务，确保进度在有效范围内
  let progress = row.progress || 0
  progress = Math.max(0, Math.min(100, progress))
  
  // 如果有分片信息，可以更精确地计算进度
  if (row.downloadedSegments && row.totalSegments && row.totalSegments > 0) {
    const segmentProgress = Math.floor((row.downloadedSegments / row.totalSegments) * 100)
    // 如果分片进度更准确，使用分片进度
    if (segmentProgress > progress || progress === 0) {
      progress = segmentProgress
    }
  }
  
  // 如果进度为0但有下载数据，尝试计算进度
  if (progress === 0 && row.downloadedSize && row.totalSize && row.totalSize > 0) {
    progress = Math.floor((row.downloadedSize / row.totalSize) * 100)
  }
  
  // 调试进度信息
  if (row.status === 'downloading' && progress > 0) {
    console.log(`Task ${row.id} progress: ${progress}%, segments: ${row.downloadedSegments || 0}/${row.totalSegments || 0}, size: ${row.downloadedSize || 0}/${row.totalSize || 0}`)
  }
  
  // 添加更详细的调试信息
  if (row.status === 'downloading') {
    console.log(`getDisplayProgress for task ${row.id}:`, {
      status: row.status,
      progress: row.progress,
      downloadedSize: row.downloadedSize,
      totalSize: row.totalSize,
      downloadedSegments: row.downloadedSegments,
      totalSegments: row.totalSegments,
      calculatedProgress: progress
    })
  }
  
  // 强制触发响应式更新
  forceRefresh.value
  
  return progress
}

// 调试进度信息
const debugProgress = (row) => {
  console.log('=== Debug Progress Info ===')
  console.log('Task ID:', row.id)
  console.log('Task Status:', row.status)
  console.log('Progress:', row.progress + '%')
  console.log('Downloaded Size:', row.downloadedSize || 0)
  console.log('Total Size:', row.totalSize || 0)
  console.log('Downloaded Segments:', row.downloadedSegments || 0)
  console.log('Total Segments:', row.totalSegments || 0)
  console.log('Segments:', row.segments || [])
  console.log('Failed Segments:', row.failedSegments || [])
  console.log('Display Progress:', getDisplayProgress(row) + '%')
  console.log('=======================')
}
</script>

<style scoped>
.task-list-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 0;
}

/* 顶部导航栏 */
.top-navbar {
  background: #ffffff;
  border-bottom: 1px solid #e4e7ed;
  padding: 20px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.nav-left {
  display: flex;
  align-items: center;
}

.app-title {
  display: flex;
  align-items: center;
  gap: 16px;
}

.title-icon {
  width: 48px;
  height: 48px;
  background: #409eff;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ffffff;
  font-size: 24px;
}

.title-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.title-text {
  margin: 0;
  font-size: 24px;
  font-weight: 700;
  color: #303133;
  line-height: 1.2;
}

.title-subtitle {
  font-size: 14px;
  color: #909399;
  font-weight: 400;
}

.nav-right {
  display: flex;
  gap: 12px;
  align-items: center;
}

.nav-btn {
  color: #606266;
  font-size: 14px;
  padding: 10px 16px;
  border-radius: 6px;
  transition: all 0.3s;
}

.nav-btn:hover {
  background: #f5f7fa;
  color: #409eff;
}

.primary-btn {
  background: #409eff;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  transition: all 0.3s;
}

.primary-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.4);
}

/* 统计区域 */
.stats-section {
  padding: 24px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.stat-card {
  background: #ffffff;
  border-radius: 12px;
  padding: 24px;
  display: flex;
  align-items: center;
  gap: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #e4e7ed;
  transition: all 0.3s;
  position: relative;
  overflow: hidden;
}

.stat-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: #409eff;
  opacity: 0;
  transition: opacity 0.3s;
}

.stat-card:hover::before {
  opacity: 1;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.stat-card.active::before {
  background: #409eff;
  opacity: 1;
}

.stat-card.completed::before {
  background: #67c23a;
  opacity: 1;
}

.stat-card.failed::before {
  background: #f56c6c;
  opacity: 1;
}

.stat-card.paused::before {
  background: #e6a23c;
  opacity: 1;
}

.stat-card.pending::before {
  background: #909399;
  opacity: 1;
}

.stat-icon {
  width: 56px;
  height: 56px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #ffffff;
}

.active-icon {
  background: #409eff;
}

.completed-icon {
  background: #67c23a;
}

.failed-icon {
  background: #f56c6c;
}

.paused-icon {
  background: #e6a23c;
}

.pending-icon {
  background: #909399;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 32px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 8px;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  font-weight: 500;
}

/* Tab区域 */
.tab-section {
  padding: 0 24px;
}

.tab-container {
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #e4e7ed;
  overflow: hidden;
  margin-bottom: 24px;
}

.tab-header {
  display: flex;
  background: #fafafa;
  border-bottom: 1px solid #e4e7ed;
}

.tab-item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
  font-size: 14px;
  color: #606266;
}

.tab-item:hover {
  background: #f0f2f5;
  color: #409eff;
}

.tab-item.active {
  background: #ffffff;
  color: #409eff;
  border-bottom: 2px solid #409eff;
}

.tab-item .el-icon {
  font-size: 16px;
}

.tab-badge {
  position: absolute;
  top: 8px;
  right: 8px;
}

/* 表格区域 */
.table-section {
  padding: 0 24px 24px;
}

.task-table-card {
  border-radius: 12px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background: #fafafa;
  border-bottom: 1px solid #e4e7ed;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.task-count {
  font-size: 14px;
  color: #909399;
  background: #f0f2f5;
  padding: 4px 12px;
  border-radius: 12px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.action-btn {
  color: #606266;
  font-size: 14px;
  padding: 8px 16px;
  border-radius: 6px;
  transition: all 0.3s;
}

.action-btn:hover {
  background: #f5f7fa;
  color: #409eff;
}

.action-btn.warning:hover {
  background: #fef0f0;
  color: #f56c6c;
}

/* 表格样式 */
.task-table {
  border: none;
}

.task-table :deep(.el-table__header) {
  background: #fafafa;
}

.task-table :deep(.el-table__header th) {
  background: #fafafa;
  border-bottom: 1px solid #e4e7ed;
  color: #606266;
  font-weight: 600;
  font-size: 14px;
}

.task-table :deep(.el-table__row) {
  transition: all 0.3s;
}

.task-table :deep(.el-table__row:hover) {
  background: #f5f7fa;
}

.row-completed {
  background: #f0f9ff;
}

.row-error {
  background: #fef0f0;
}

.row-paused {
  background: #fef9e7;
}

.row-downloading {
  background: #f0f9ff;
}

/* 文件名单元格 */
.filename-cell {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.file-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.filename {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  line-height: 1.4;
}

.file-meta {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #909399;
}

.file-tags {
  display: flex;
  gap: 6px;
}

.file-tag {
  border-radius: 4px;
  font-size: 11px;
}

/* 状态单元格 */
.status-cell {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.status-tag {
  border-radius: 6px;
  font-weight: 500;
}

.status-time {
  font-size: 11px;
  color: #909399;
}

/* 进度单元格 */
.progress-cell {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.progress-percentage {
  font-size: 14px;
  font-weight: 600;
  color: #409eff;
}

.progress-segments {
  font-size: 12px;
  color: #909399;
  background: #f0f2f5;
  padding: 2px 8px;
  border-radius: 10px;
}

.custom-progress :deep(.el-progress-bar__outer) {
  background: #f0f2f5;
  border-radius: 3px;
}

.custom-progress :deep(.el-progress-bar__inner) {
  border-radius: 3px;
}

.progress-details {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #909399;
}

.speed-info {
  color: #67c23a;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 4px;
}

.speed-icon {
  font-size: 12px;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.6; }
  100% { opacity: 1; }
}

.merge-info {
  color: #e6a23c;
  font-weight: 500;
}

.remaining-time {
  color: #909399;
  font-size: 11px;
  font-style: italic;
}

/* 分片信息 */
.segments-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 11px;
  margin-top: 4px;
  padding: 2px 6px;
  background: #f8f9fa;
  border-radius: 4px;
}

.segments-text {
  color: #606266;
}

.failed-segments {
  color: #f56c6c;
  font-weight: 500;
}

/* 线程数单元格 */
.threads-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.threads-number {
  font-size: 16px;
  font-weight: 600;
  color: #409eff;
}

.threads-label {
  font-size: 11px;
  color: #909399;
}

/* 时间单元格 */
.time-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.start-time {
  font-size: 14px;
  color: #303133;
}

.duration {
  font-size: 11px;
  color: #909399;
}

/* 操作单元格 */
.actions-cell {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
}

.actions-cell .action-btn {
  padding: 6px 12px;
  font-size: 12px;
  border-radius: 4px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .stats-grid {
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  }
  
  .nav-title {
    display: none;
  }
}

@media (max-width: 768px) {
  .top-navbar {
    padding: 16px;
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .nav-right {
    justify-content: center;
  }
  
  .stats-section {
    padding: 16px;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .tab-section {
    padding: 0 16px;
  }
  
  .table-section {
    padding: 0 16px 16px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: center;
  }
}
</style>